/** *******************************************************************
 * FlexDatabaseManager
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.accounts
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.accounts.GetUserInfoEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class GetUserInfoCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:GetUserInfoEvent = event as GetUserInfoEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				delegate.getUserInfo( model.currentUser );
		}

		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var resultObj:ResultEvent = data as ResultEvent;
			
			//model.mysqlInfoCollection = parseJSONResult( event.result );
			if ( resultObj is String )
			{
				//get the raw JSON data and cast to String
				var rawData:String = String( resultObj );

				//decode the data to ActionScript 
				var tempArray:Array = ( JSON.decode( rawData ) as Array );
				
				var u:UserVO = new UserVO( resultObj.token.user.host,
										   resultObj.token.user.port,
										   resultObj.token.user.username,
										   resultObj.token.user.password, 
										   tempArray[0]['Fullname'] as String,
										   tempArray[0]['Description'] as String,
										   tempArray[0]['Email'] as String,
										   tempArray[0]['Info'] as String,
										   tempArray[0]['Icon'] as String );
					
				model.currentUser = u;
			}
			
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}